<?php declare(strict_types=1);

include __DIR__ . '/../application/units/Di.php';

// 初始化容器
$di = \application\units\Di::getInstance();

// 注册config服务
$di->config = function () {
    return [
        'database' => require __DIR__ . '/../config/database.php',
        'common'   => require __DIR__ . '/../config/common.php',
    ];
};

$di->router = function () {
    return include __DIR__ . '/../bootstrap/router.php';
};

// 注册DB服务
$di->db = function () {
    include_once __DIR__ . '/../application/units/Db.php';
    $dsn      = sprintf('%s:host=%s;port=%s;dbname=%s;charset=%s',
        $this->config['database']['driver'],
        $this->config['database']['host'],
        $this->config['database']['port'],
        $this->config['database']['dbname'],
        $this->config['database']['charset']
    );
    $username = $this->config['database']['username'];
    $password = $this->config['database']['password'];
    $option   = $this->config['database']['option'] + [
            PDO::ATTR_CASE               => PDO::CASE_NATURAL,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_ORACLE_NULLS       => PDO::NULL_NATURAL,
            PDO::ATTR_STRINGIFY_FETCHES  => false,
            PDO::ATTR_EMULATE_PREPARES   => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ];
    return new \application\units\Db($dsn, $username, $password, $option);
};

// 注册request服务
$di->request = function () {
    include_once __DIR__ . '/../application/units/Request.php';
    return new \application\units\Request();
};

// 注册auth服务
$di->auth = function () {
    include_once __DIR__ . '/../application/units/Auth.php';
    return new \application\units\Auth($this);
};

// 注册tree服务
$di->tree = function () {
    include_once __DIR__ . '/../application/units/Tree.php';
    return new \application\units\Tree();
};

$di->businessCommonQuery = function () {
    include_once __DIR__ . '/../application/units/BusinessCommonQuery.php';
    return new \application\units\BusinessCommonQuery($this);
};

return $di;